﻿using System;
using UnityEngine;

namespace Core.Extension
{
    /// <summary>
    /// 单例Mono对象
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class SingletonMono<T> : MonoBehaviour where T : SingletonMono<T>
    {
        private static object lockObj = new object();
        private static T _ins;

        public static T Ins
        {
            get
            {
                lock (lockObj)
                {
                    if (_ins == null)
                    {
                        if (FindObjectsOfType(typeof(T)).Length > 1)
                        {
                            throw new Exception("单例被多个对象使用");
                        }
                        _ins = (T) FindObjectOfType(typeof(T));
                        if (_ins == null)
                        {
                            GameObject singleton = new GameObject();
                            _ins = singleton.AddComponent<T>();
                            singleton.name = "(singleton) " + typeof(T);
                            DontDestroyOnLoad(singleton);
                        }
                    }

                    return _ins;
                }
            }
            private set => _ins = value;
        }
    }
}